package pers.corvey.studyjava.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import pers.corvey.studyjava.MyConstant;

public class FileUtils {

    public static File saveString(String pathName, String content, String extension) 
            throws IOException {
        String contentMD5 = EncodingUtils.encodeByMD5(content);
        if (!extension.startsWith(".")) {
            extension = "." + extension;
        }
        String fileName = contentMD5 + extension;
        File file = new File(MyConstant.CLASS_STATIC_PATH + pathName, fileName);
        saveString(file, content);
        File backupFile = new File(MyConstant.BACKUP_STATIC_PATH + pathName, fileName);
        saveString(backupFile, content);
        return file;
    }
    
    public static boolean deleteFile(String fileName) {
        File file = new File(MyConstant.CLASS_STATIC_PATH, fileName);
        return file.delete();
    }
    
    public static String getFileExtension(String fileName) {
        Pattern pattern = Pattern.compile(".(\\w+)$");
        Matcher matcher = pattern.matcher(fileName);
        return matcher.find() ? matcher.group(0) : "";  
    }
    
    private static void saveString(File file, String content) throws IOException {
        if (!file.exists()) {
            try (FileWriter fw = new FileWriter(file)) {
                fw.write(content);
            }
        }
    }
}
